import React, { PureComponent, Fragment } from 'react'
import { connect } from "react-redux";


import { Layout } from 'antd';
import {
    PageHeader,
    ButtonEvent,
    Form,
    Tip,
} from '../../../components';
import { mainService } from '../../../service';
import { cmsSettingAction as actionCreates, mainAction } from '../../../store/action';

const breadcrumbList = [{
    title: '页面管理'
}, {
    title: '系统设置'
}];

class Index extends PureComponent{
    state = {
        //api名称
        apiname:'cms/setting',
        visible:false,
        modalTitle:"系统设置",
        
        //form表单
        inputdata : [],
        footerbar:null,
        footBar:[],
    }
    render(){
        const { inputdata } = this.state;

        const action = <ButtonEvent data={ [
            {key:1,type:'primary',value:'刷新',size:'small',onClick:()=>{
                this.reset()
            }}
        ]}/>;

        return(
            <Fragment>
                <PageHeader title={breadcrumbList[1]['title']} breadcrumbList={breadcrumbList} action={action}></PageHeader>

                <Layout.Content style={{margin:'24px',padding:'24px 32px 80px',position:'relative',backgroundColor:'#fff'}}>
                    <Form
                        layout = 'horizontal'
                        data = {inputdata}
                        wrappedComponentRef={(form) => this.formRef = form}
                    />
                    
                    <div
                        style={{
                            position: 'absolute',
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e8e8e8',
                            padding: '10px 16px',
                            textAlign: 'right',
                            left: 0,
                            background: '#fff',
                            borderRadius: '0 0 4px 4px',
                        }}
                    >
                        <ButtonEvent data={ [
                            {key:1,type:'primary',value:'保存',btnloading:1,onClick:()=>{
                                this.saveSetting()
                            }}
                        ]}/>
                    </div>
                </Layout.Content>
            </Fragment>
        )
    }

    saveSetting = async ()=>{
        const { apiname } = this.state;
        const { data } = this.props;
        this.changeBtnLoading(true);
        let values = await this.formRef.getItemsValue();
        if(values){
            try{
                let config = {
                    title:values['title'],
                    keywords:values['keywords'],
                    description:values['description'],
                    template:values['template'],
                }
                let newData ={
                    id:values['id'],
                    name:data['name'],
                    config:JSON.stringify(config)
                }
                let res = await mainService.crud(apiname+"/edit",newData);
                this.tipMsg(res);
            }catch{
                this.tipMsg({code:3,msg:"网络错误"});
            }
        }
        setTimeout(()=>{
            this.changeBtnLoading(false);
        },500);
    }
    //保存按钮状态
    changeBtnLoading = (bool)=>{
        this.props.bindBtnLoading(bool)
    }
    //消息提示
    tipMsg = (res)=>{
        if(res.code===0){
            Tip.Message(res.msg,'success');
        }else{
            Tip.Message(res.msg,'error')
        }
    }

	//重置/刷新查询
    reset = () => {
        const { bindLoading, pageSize, page } = this.props;
        bindLoading(true)
        this.loadList({page,rows:pageSize})
    }
    
	//获取列表
    loadData = async ()=>{
        const { bindData } = this.props;
        const { apiname } = this.state;
        let res = await mainService.find(apiname);
	
        bindData(res);

        let obj = res.data;
        const { formData } = this.props;
        let dcont = JSON.parse(obj.config);
        //初始化添加的form表单数据
        let formDataArr=[];
        for (let i=0;i<formData['arr'].length;i++) {
            let v = formData['arr'][i];
            let o = {};
            o = Object.assign({},formData[v]);
            o.value = dcont[v];
            formDataArr.push(o)
        }

        let id = {type:'input.hidden',title:'ID',name:'id',value:obj['id'],disabled:true};
        formDataArr.push(id);
        this.setState({
            inputdata:formDataArr
        });
    }

	async componentDidMount(){
        this.loadData()
    }
}

const mapStateToProps = (state)=>{
    const name = 'cms_setting';

    const loading = state.getIn([name,'loading']);
    const formData = state.getIn([name,'formData']).toJS();
    const data = state.getIn([name,'data']).toJS();
    
    const btnloading = state.getIn(['main','btnloading']);
    

    return{
        data,
        loading,
        formData,

        btnloading,

    }
}
const mapDispatchToProps = (dispatch)=>{
    return{
        bindLoading(loading){
            dispatch(actionCreates.setLoading(loading))
        },
        bindData(res){
            if(res.code === 0){
                let data=res.data;
                dispatch(actionCreates.getData(data));
            }else{
                dispatch(actionCreates.setEmptyText(res.msg));
            }
            dispatch(actionCreates.setLoading(false));
        },
        bindBtnLoading(bool){
            dispatch(mainAction.setBtnLoading(bool));
        },
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(Index);